# -*- coding: utf-8 -*-

################################################################################
## Form generated from reading UI file 'searchFilter.ui'
##
## Created by: Qt User Interface Compiler version 6.3.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################


from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
    QMetaObject, QObject, QPoint, QRect, qDebug,
    QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
    QFont, QFontDatabase, QGradient, QIcon, QAction,
    QImage, QKeySequence, QLinearGradient, QPainter,
    QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QCheckBox, QComboBox, QGroupBox, QLabel,
    QPushButton, QRadioButton, QSizePolicy, QVBoxLayout, QButtonGroup, QLayout, QMenu,
    QListWidgetItem, QWidget, QHBoxLayout, QGridLayout)
from Libs.Component.ComboCheckBox import ComboCheckBox
import math

class SearchFilterForm(object):
    def setupUi(self, Form):
        if not Form.objectName():
            Form.setObjectName(u"Form")
        self.width = 450
        self.height = 475
        Form.resize(self.width, self.height)
        self.horizontalLayout = QHBoxLayout(Form)
        self.horizontalLayout.setObjectName(u"horizontalLayout")
        self.verticalLayout = QVBoxLayout(Form)
        self.gridLayout = QVBoxLayout()
        self.gridLayout.setObjectName(u"verticalLayout")

        # self.widget = QWidget(Form)
        # self.widget.setObjectName(u"widget")
        # self.widget.setGeometry(QRect(10, 10, 611, 501))

        self.contentType = QGroupBox('contentType')
        self.contentType.setObjectName(u"contentType")
        self.gridLayout.addWidget(self.contentType)
        self.contentTypeLayout = QGridLayout(self.contentType)

        self.salesData = QGroupBox('salesData')
        self.salesData.setObjectName(u"salesData")
        self.gridLayout.addWidget(self.salesData)
        self.salesDataLayout = QGridLayout(self.salesData)

        self.uploaderInfos = QGroupBox('uploaderInfos')
        self.uploaderInfos.setObjectName(u"uploaderInfos")
        self.gridLayout.addWidget(self.uploaderInfos)
        self.uploaderInfosLayout = QGridLayout(self.uploaderInfos)

        self.cooperationInfos = QGroupBox('cooperationInfos')
        self.cooperationInfos.setObjectName(u"cooperationInfos")
        self.gridLayout.addWidget(self.cooperationInfos)
        self.cooperationInfosLayout = QGridLayout(self.cooperationInfos)

        self.verticalLayout.addLayout(self.gridLayout)

        self.searchBtn = QPushButton()
        self.searchBtn.setObjectName(u"searchBtn")
        self.searchBtn.setText("保存搜索条件")

        self.verticalLayout.addWidget(self.searchBtn)


        self.horizontalLayout.addLayout(self.verticalLayout)


        # self.retranslateUi(Form)

        QMetaObject.connectSlotsByName(Form)

    def setLayout(self, parent, item, idx = 0, pos = 0, splitter=3):
        line = math.ceil(pos / splitter)
        column = idx % splitter

        if parent.objectName() == 'salesData':
            self.salesDataLayout.addLayout(item, line, column)
        if parent.objectName() == 'cooperationInfos':
            if isinstance(item, QLayout):
                self.cooperationInfosLayout.addLayout(item, line, column)
            else:
                self.cooperationInfosLayout.addWidget(item, line, column, Qt.AlignmentFlag.AlignLeft)
        if parent.objectName() == 'uploaderInfos':
            if isinstance(item, QLayout):
                self.uploaderInfosLayout.addLayout(item, line, column)
            else:
                self.uploaderInfosLayout.addWidget(item, line, column)
        if parent.objectName() == 'contentType':
            if isinstance(item, QLayout):
                self.contentTypeLayout.addLayout(item, line, column)
            else:
                self.contentTypeLayout.addWidget(item, line, column)

    def _parseLayout(self, parent, data):
        """
        设置layout
        """
        layoutName = f"{data.get('field_name')}_layout"
        if not hasattr(self, layoutName):
            setattr(self, layoutName, QHBoxLayout())
        layout = getattr(self, layoutName)

        labelName = f"{data.get('field_name', '')}_label"
        if not hasattr(self, labelName):
            setattr(self, labelName, QLabel(parent))
        label = getattr(self, labelName)
        label.setText(data.get('name', ''))
        layout.addWidget(label, alignment=Qt.AlignmentFlag.AlignLeft)

        return layout
    
    # setupUi
    def _parseFieldName(self, field_name):
        itemName = ""
        for i, x in enumerate(field_name):
            itemName += x if i == 0 else x.capitalize()
        return itemName
    
    def _parseBool(self, parent, idx, pos, data):
        radioGroupName = f"button_group_{data.get('field_name', '')}"
        if not hasattr(self, radioGroupName):
            setattr(self, radioGroupName, QButtonGroup(parent))
        radioGroup = getattr(self, radioGroupName)

        itemName = f"query_body_{data.get('field_name', '')}"
        if not hasattr(self, itemName):
            # setattr(self, itemName, QRadioButton(parent))
            # setattr(self, itemName, QPushButton(parent))
            setattr(self, itemName, QCheckBox(parent))
        item = getattr(self, itemName)

        item.setCheckable(True)
        item.setChecked(False)
        item.setCheckState(Qt.CheckState.Unchecked)
        item.setObjectName(data.get('field_name', ''))
        item.setText(data.get('name', ''))
        radioGroup.setExclusive(True)
        # radioGroup.addButton(item, True)
        
        self.setLayout(parent, item, idx, pos)

    def _parseMenuButton(self, parent, idx, pos, data):
        layout = self._parseLayout(parent, data)
        itemName = f"query_body_{data.get('field_name', '')}_{idx}"

    def _parseText(self, parent, idx, pos, data):
        itemName = f"query_body_{data.get('field_name', '')}_{idx}"

        if not hasattr(self, itemName):
            setattr(self, itemName, QCheckBox(parent))
        item = getattr(self, itemName)
        item.setObjectName(data.get('name'))
        item.setText(data.get('name'))

        self.setLayout(parent, item, idx, pos)
        
    def _parseRadio(self, parent, idx, pos, data):
        layout = self._parseLayout(parent, data)
        # itemName = self._parseFieldName(data.get('field_name', '').split('_'))
        itemName = f"query_body_{data.get('field_name', '')}"

        if not hasattr(self, itemName):
            setattr(self, itemName, QComboBox(parent))
        item = getattr(self, itemName)
        item.setToolTip(data.get('name', ''))
        for value, child in enumerate(data.get('children', [])):
            item.addItem(child.get('name', '全部'), value)
        layout.addWidget(item)
        
        self.setLayout(parent, layout, idx, pos)
                
    def _parseContentType(self, parent, title, idx, pos, data):
        buttonGroupName = self._parseFieldName(data.get('field_name', '').split('_'))
        buttonGroupName = f'{buttonGroupName}ButtonGroup'
        if not hasattr(self, buttonGroupName):
            setattr(self, buttonGroupName, QButtonGroup(parent))
        buttonGroup = getattr(self, buttonGroupName)

        itemName = f"query_body_{data.get('field_name', '')}_{idx}"
        if not hasattr(self, itemName):
            setattr(self, itemName, QPushButton(parent))
        item = getattr(self, itemName)
        item.setObjectName(data.get('field_name', ''))
        item.setText(data.get('name', ''))
        item.setCheckable(True)
        item.setChecked(False)
        line = math.ceil(pos / 4)
        column = idx % 4
        width = math.floor((self.width - 3 * 5) / 4)
        x, y, w, h = (column * width) + 5, 30 * line, width, 20
        item.setGeometry(QRect(x, y, w, h))
        item.setMinimumSize(100, 20)
        item.setAutoExclusive(True)

        buttonGroup.addButton(item)
        # buttonGroup.setAutoExclusive(False)

    def parseCooperationInfos(self, title, idx, pos, data):
        # self.cooperationInfos.setObjectName(title)
        self.cooperationInfos.setTitle(title)
        componentType = data.get('type', 'bool')

        if componentType in ['bool']:
            self._parseBool(self.cooperationInfos, idx, pos, data)
        elif componentType in ["cascade", "ratio"]:
            self._parseRadio(self.cooperationInfos, idx, pos, data)
        elif componentType in ['checkbox']:
            self._parseCheckBox(self.cooperationInfos, idx, pos, data)
        
    def parseUploaderInfos(self, title, idx, pos, data):
        self.uploaderInfos.setTitle(title)
        componentType = data.get('type', 'checkbox')

        # ratio
        # if componentType in ["checkbox", "cascade", "ratio"]:
        if componentType in ["ratio"]:
            self._parseRadio(self.uploaderInfos, idx, pos, data)
        elif componentType in ["cascade"]:
            self._parseCascade(self.uploaderInfos, idx, pos, data)
        elif componentType in ["agg"]:
            self._parseCascade(self.uploaderInfos, idx, pos, data, secondItemName=componentType == 'agg')
        elif componentType in ["checkbox"]:
            self._parseCheckBox(self.uploaderInfos, idx, pos, data)

    def _parseCascade(self, parent, idx, pos, data, secondItemName=False):
        layout = self._parseLayout(parent, data)

        itemName = f"query_body_{data.get('field_name')}"
        if not hasattr(self, itemName):
            # item = setattr(self, itemName, QMenu(data.get('field_name')))
            item = setattr(self, itemName, QPushButton(parent))
        item = getattr(self, itemName)
        item.setMinimumSize(75, 20)
        item.setObjectName(itemName)
        qDebug(f'cascade: {itemName}')
        menu = QMenu(parent)
        for x in data.get('children'):
            item.setMenu(menu)
            parentObjectName = x.get('name')
            if x.get('children', []):
                submenu = menu.addMenu(x.get('name'))
                for y in x.get('children', []):
                    if secondItemName:
                        secondItemName = f"query_body_{x.get('field_name')}"
                        actionName = f"{secondItemName}_{y.get('value')}"
                        if not hasattr(self, secondItemName):
                            setattr(self, secondItemName, QLabel(parent))
                    else:
                        actionName = f"query_body_{data.get('field_name')}_{x.get('value')}|{y.get('value')}"
                    qDebug(f'actionName: {actionName} - {itemName} - {x.get("field_name")}')
                    if not hasattr(self, actionName):
                        setattr(self, actionName, QAction(y.get('name')))
                    action = getattr(self, actionName)
                    action.setObjectName(actionName)
                    action.setToolTip(f'{parentObjectName}_{y.get("name")}')
                    action.setCheckable(True)
                    submenu.addAction(action)
            else:
                item.addAction(x.get('name'))
        layout.addWidget(item)

        self.setLayout(parent, layout, idx, pos)

    def _parseCheckBox(self, parent, idx, pos, data):
        layout = self._parseLayout(parent, data)

        itemName = f"query_body_{data.get('field_name', data.get('name'))}"
        if not hasattr(self, itemName):
            v = [child.get("name", "全部") for child in data.get('children', [])]
            setattr(self, itemName, ComboCheckBox(parent, v))
        item = getattr(self, itemName)
        item.setToolTip(data.get('name', ''))
        layout.addWidget(item)
        
        self.setLayout(parent, layout, idx, pos)

    def parseSalesData(self, title, idx, pos, data):
        self.salesData.setTitle(title)
        componentType = data.get('type', 'checkbox')

        if componentType == "checkbox":
            # self._parseRadio(self.salesData, idx, pos, data)
            self._parseCheckBox(self.salesData, idx, pos, data)

    def parseContentType(self, title, idx, pos, data):
        # self.contentType.setObjectName(title)
        self.contentType.setTitle(title)             
        componentType = data.get('type', 'text')
        
        if componentType == "text":
            # self._parseText(self.contentType, idx, pos, data)
            self._parseContentType(self.contentType, title, idx, pos, data)

    def parseData(self, data):
        for info in data:
            componentTitle = info.get("name")
            componentName, component = '', None
            headers = info.get('header', [])
            if not headers:
                continue
            if not componentName:
                temp_header = headers[0]
                for idx, x in enumerate(temp_header.get('field_name', '').split('_')):
                    componentName += x if idx == 0 else x.capitalize()
            if componentTitle == '内容类型':
                contentTypeData = {
                    'name': componentTitle,
                    'type': 'checkbox',
                    'field_name': 'content_type',
                    'children': info.get('header', [])
                }
                self.contentType.setTitle(componentTitle)  
                self._parseCheckBox(
                    self.contentType, 0, 1, contentTypeData
                )
                self.parseDarenType()

            for i, header in enumerate(headers):
                pos = i + 1

                if componentTitle == '带货数据':
                    self.parseSalesData(componentTitle, i, pos, header)
                # elif componentTitle == '内容类型':
                #     self.parseContentType(componentTitle, i, pos, header)
                elif componentTitle == '达人信息':
                    self.parseUploaderInfos(componentTitle, i, pos, header)
                elif componentTitle == '合作信息':
                    self.parseCooperationInfos(componentTitle, i, pos, header)

    def parseDarenType(self, data=[]):
        data = ['全部达人', '直播达人', '视频达人', '图文达人', '橱窗达人']
        layout = self._parseLayout(self.contentType, {'field_name': 'daren_type', 'name': '达人类型'})
        # itemName = self._parseFieldName(data.get('field_name', '').split('_'))
        itemName = f"daren_type"

        if not hasattr(self, itemName):
            setattr(self, itemName, QComboBox(self.contentType))
        item = getattr(self, itemName)
        item.setToolTip('达人类型')
        for name in data:
            item.addItem(name)
        layout.addWidget(item)
        
        self.setLayout(self.contentType, layout, 1, 1)


    def retranslateUi(self, Form):
        Form.setWindowTitle(QCoreApplication.translate("Form", u"Form", None))
        self.contentType.setTitle(QCoreApplication.translate("Form", u"\u5185\u5bb9\u7c7b\u578b", None))
        self.data.setTitle(QCoreApplication.translate("Form", u"\u5e26\u8d27\u6570\u636e", None))
        self.uploaderInfos.setTitle(QCoreApplication.translate("Form", u"\u8fbe\u4eba\u4fe1\u606f", None))
        self.cooperationInfos.setTitle(QCoreApplication.translate("Form", u"\u5408\u4f5c\u4fe1\u606f", None))
        self.searchBtn.setText(QCoreApplication.translate("Form", u"\u786e\u5b9a", None))
    # retranslateUi

